package com.freely.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.entities.Group;
import com.freely.ui.activities.CreateGroupActivity;
import com.freely.ui.activities.PhotoSelectActivity;
import com.freely.ui.util.DataVerification;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.util.VerificationUtil;
import com.freely.ui.viewModel.DetailViewModel;
import com.freely.ui.viewModel.GroupEditViewModel;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;


public class GroupInformationEditActivity extends NavigationActivity {
	@BindView(R2.id.group_head_icon)
	ImageView groupHeadIcon;
	@BindView(R2.id.group_name_layout)
	TextInputLayout groupNameLayout;
	@BindView(R2.id.group_name)
	TextInputEditText groupName;
	@BindView(R2.id.group_notice_layout)
	TextInputLayout groupNoticeLayout;
	@BindView(R2.id.group_notice)
	TextInputEditText groupNotice;


	private long groupId;
	private String headIconPath;
	private GroupEditViewModel groupEditModel;
	private BottomSheetDialog dialog;
	private Bitmap headIconBitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_information_edit);
		init();
	}

	@Override
	protected void onCreateToolbar(Toolbar toolbar, TextView title, ImageButton logo) {
		super.onCreateToolbar(toolbar, title, logo);
		toolbar.inflateMenu(R.menu.detail_edit);
		toolbar.setOnMenuItemClickListener(item -> {
			switch(item.getItemId()){
				case R.id.finish:{
					if(!groupNameLayout.isErrorEnabled() && !groupNoticeLayout.isErrorEnabled()){
						if(updateGroupInformation()){
                            Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT).show();
                        }
					}else {
						Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT).show();
					}
					break;
				}
			}
			return false;
		});
	}

	private boolean updateGroupInformation() {
		Group group = groupEditModel.getGroupInformation().getValue();
		Group updateGroup = new Group();
		updateGroup.setGroupId(group.getGroupId());
		updateGroup.setGroupAdmin(group.getGroupAdmin());

		String editGroupName = groupName.getText().toString();
		String editGroupNotice = groupNotice.getText().toString();
		boolean flag = false;
		if(!editGroupName.equals(group.getGroupName())){
			updateGroup.setGroupName(editGroupName);
			flag = true;
		}
		if(editGroupNotice.length() > 0 && !editGroupNotice.equals(group.getGroupNotice())){
			updateGroup.setGroupNotice(editGroupNotice);
			flag = true;
		}
		if(headIconBitmap == null && !flag){
			return false;
		}
		Disposable disposable = Single.just(updateGroup)
				.subscribeOn(Schedulers.io())
				.subscribe(temp -> {
					if(headIconBitmap != null){
						//头像由bitmap转为base64
						ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
						headIconBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
						byte[] headIconByte = outputStream.toByteArray();
						updateGroup.setGroupImage( ByteString.of(headIconByte).base64());
					}
					//发送更新请求
					groupEditModel.updateGroupInformation(updateGroup);

				}, throwable -> {
					//头像错误
					ErrorUtil.dataReadErrorHint("头像错误",throwable);
				});
		register(disposable);
		return true;
	}

	public static void startActivity(Activity activity, long groupId) {
		Intent intent = new Intent(activity, GroupInformationEditActivity.class);
		intent.putExtra(Group.group_id, groupId);
		activity.startActivity(intent);
	}

	private void init(){
		groupId = getIntent().getLongExtra(Group.group_id,-1L);
		groupEditModel = new GroupEditViewModel(this);
		groupEditModel.loadGroupInformation(groupId);
		groupEditModel.getGroupInformation().observe(this,group -> {
			groupName.setText(group.getGroupName());
			if(group.getGroupNotice() != null && group.getGroupNotice().trim().length() > 0){
				groupNotice.setText(group.getGroupNotice());
			}
			byte[] headIconByte = Base64.decode(group.getGroupImage(), Base64.DEFAULT);
			Glide.with(this)
					.load(headIconByte)
					.apply(RequestOptions.circleCropTransform())
					.into(groupHeadIcon);
		});
	}

	@OnTextChanged(R.id.group_name)
	void groupNameTextChangedListener(Editable edit){
		VerificationUtil.groupNameVerificationHint(edit.toString(),groupNameLayout,"群名称长度为1-20");
	}

	@OnTextChanged(R.id.group_notice)
	void groupNoticeTextChangedListener(Editable edit){
		VerificationUtil.groupIntroVerificationHint(edit.toString(),groupNoticeLayout,"群公告长度为0-100");
	}

	@OnClick(R.id.group_head_icon)
	void selectHeadIcon(){
		if (dialog == null) {
			View view = LayoutInflater.from(this).inflate(R.layout.dialog_photo_select, null);
			TextView capture = view.findViewById(R.id.capture);
			TextView gallery = view.findViewById(R.id.gallery);
			capture.setOnClickListener(this::groupHeadIconSelect);
			gallery.setOnClickListener(this::groupHeadIconSelect);
			dialog = new BottomSheetDialog(this);
			dialog.setContentView(view);
		}
		dialog.show();
	}

	void groupHeadIconSelect(View view) {
		switch (view.getId()) {
			case R.id.capture:
				//相机选取群头像
				PhotoSelectActivity.startActivity(
						GroupInformationEditActivity.this,
						CreateGroupActivity.PHOTO_SELECT,
						PhotoSelectActivity.CAPTURE
				);
				break;
			case R.id.gallery:
				//相册选取群头像
				PhotoSelectActivity.startActivity(
						GroupInformationEditActivity.this,
						CreateGroupActivity.PHOTO_SELECT,
						PhotoSelectActivity.GALLERY
				);
				break;
		}
		dialog.cancel();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		switch (requestCode) {
			case CreateGroupActivity.PHOTO_SELECT:
				Log.d("detail", "onActivityResult: 图片选择结果");
				if (resultCode != RESULT_OK) {
					return;
				}
				Log.d("detail", "onActivityResult: 成功选择图片");
				headIconPath = data.getStringExtra(PhotoSelectActivity.RESULT);
				Log.d("detail", "onActivityResult: 判断图片路径");
				if (TextUtils.isEmpty(headIconPath)) {
					return;
				}
				Log.d("detail", "onActivityResult: 图片路径正确");
				Glide.with(this)
						.asBitmap()
						.load(new File(headIconPath))
						.apply(RequestOptions.circleCropTransform())
						.listener(new RequestListener<Bitmap>() {
							@Override
							public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
								return false;
							}
							@Override
							public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
								headIconBitmap = resource;
								return false;
							}
						})
						.into(groupHeadIcon);
				break;
		}
	}


}
